<?php

/**
 * uniBoard ACP index page
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date: 2010-09-06 01:45:14 +0000 (Mon, 06 Sep 2010) $
 * $Revision: 59 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class action_login{
	
	/**
	 * Main class pointer
	 *
	 * @var object
	 */
	
	private $appCore			= NULL;
	
	/**
	 * Our Log-In manager
	 *
	 * @var object
	 */
	
	private $login_mgr			= NULL;
	
	/**
	 * Return link after successful
	 *
	 * @var string
	 */
	
	private $return_link 		= null;
	
	/**
	 * Error message to display
	 *
	 * @var string
	 */
	
	private $message 			= null;
	
	/**
	 * User-typed login
	 *
	 * @var string
	 */
	
	private $user_login 		= null;
	
	/**
	 * Failed Log In Attemps
	 *
	 * @var integer
	 */
	
	private $login_attempts		= 0;
	
	// ------------------------------------------------------------------------

	/**
	 * Initialise Action
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Store appCore pointer
		$this -> appCore = $appCore;
	
		// Start log-in manager
		$this -> login_mgr = new class_login( $appCore);
			
		// Are we in admin?
		if ( IN_ADMIN && $this -> appCore -> session -> session_error > 1)
		{
			// Display message from session?
			switch ( $this -> appCore -> session -> session_error)
			{
				case 2:
					// Session timed out
					$this -> message = $appCore -> lang['login_form_message_session_timed_out'];
				break;
							
				case 3:
					// Session died due to permissions
					$this -> message = $appCore -> lang['login_form_message_session_not_admin'];				
				break;
			}				
		}
		
		// IP locked by failed attempts?
		if ( $appCore -> conf['sessions_block_attempts'] > 0 && $appCore -> user['id'] < 1)
		{
			$this -> login_attempts = $appCore -> db -> count( 'login_attempts', 'attempt_ip = \'' . $appCore -> db -> strEscape( $appCore -> client_ip) . '\' AND attempt_date > \'' . ( $appCore -> time - ( 60 * $appCore -> conf['sessions_unblock_time'])) . '\'');
		}
		else
		{
			// Dont Count attempts
			$this -> login_attempts = 0;
		}
		
		// Block Action?
		if ( $this -> login_attempts >= $appCore -> conf['sessions_block_attempts'] && $appCore -> conf['sessions_block_attempts'] > 0)
		{
			// Set Error
			if ( IN_ADMIN)
			{
				// Set Message
				$this -> message = $appCore -> lang['login_form_message_attempts_limit'];
				
				// Draw Form anyway
				$this -> drawLoginForm();
			}
			else
			{
				// Set Message
				$appCore -> output -> setEvent( $appCore -> lang['login_form_message_attempts_limit'], $appCore -> lang['login_error'], 0);
				
				// Draw Events Page
				$appCore -> output -> drawEvents( true);
			}
		}
		else if ( $appCore -> user['id'] > 0 && $appCore -> _REQ( 'do') != 'logout')
		{
			// Set Error
			if ( IN_ADMIN)
			{
				// Show Error
				$appCore -> output -> error( $appCore -> lang['action_not_allowed_users']);
				
				// Draw Empty page
				$appCore -> output -> draw('', array(), '');
			}
			else
			{
				// Set Message
				$appCore -> output -> setEvent( $appCore -> lang['action_not_allowed_users'], '', 0);
				
				// Draw Events Page
				$appCore -> output -> drawEvents( true);
			}
		}
		else if ( !IN_ADMIN && $appCore -> user['id'] < 1 && $appCore -> banned_ip)
		{
			// Set Message
			$appCore -> output -> setEvent( ( isset( $appCore -> ban_reason[0]) ? $appCore -> ban_reason : $appCore -> lang['action_not_allowed_ip']), $appCore -> lang['wrong_action_banned'], 0);
			
			// Draw Events Page
			$appCore -> output -> drawEvents( true);
		}
		else
		{
			// Start little controler
			switch ( $this -> appCore -> _REQ( 'do'))
			{
				case 'auth':
					// Check user input and attempt to start admin session
					$this -> authUser();
				break;
				
				case 'logout':
					// Are We Logged In?
					if ( $this -> appCore -> user['id'] > 0)
					{
						// Auth Allrite?
						if ( $this -> appCore -> validRequest( false))
						{
							// Logout User
							$this -> logoutUser();
						}
						else
						{
							// Set Error
							if ( IN_ADMIN)
							{
								// Show Error
								$appCore -> output -> error( $appCore -> lang['wrong_action_auth'], $appCore -> lang['wrong_action_auth_title']);
								
								// Draw Empty page
								$appCore -> output -> draw('', array(), '');
							}
							else
							{
								// Set Message
								$appCore -> output -> setEvent( $appCore -> lang['wrong_action_auth'], $appCore -> lang['wrong_action_auth_title'], 0);
								
								// Draw Events Page
								$appCore -> output -> drawEvents( true);
							}
						}
					}
					else
					{
						// Set Error
						if ( IN_ADMIN)
						{
							// Show Error
							$appCore -> output -> error( $appCore -> lang['action_not_allowed_guest']);
							
							// Draw Empty page
							$appCore -> output -> draw('', array(), '');
						}
						else
						{
							// Set Message
							$appCore -> output -> setEvent( $appCore -> lang['action_not_allowed_guest'], '', 0);
							
							// Draw Events Page
							$appCore -> output -> drawEvents( true);
						}
					}
				break;
				
				default:
					// Draw login form
					$this -> drawLoginForm();
				break;		
			}
		}
		
	}
	
	// ------------------------------------------------------------------------
	
	/**
	 * Attempts to log-in user, or redirect back to login form
	 *
	 */
	
	function authUser(){
		
		// Get login data and put into manager
		$this -> login_mgr -> setUserLogin( $this -> appCore -> _POST( 'user_login')); 
		$this -> login_mgr -> setUserPass( $this -> appCore -> _POST( 'user_password')); 
		
		// If we are not in Admin, let's set log-in tools
		if ( !IN_ADMIN)
		{
			$this -> login_mgr -> setUserOps( $this -> appCore -> _REQ( 'login_hidden'), $this -> appCore -> _REQ( 'login_remember'));
		}

		// Authorise user
		$this -> login_mgr -> authUser();
			
		// If log-in attempt failed, handle error
		if ( $this -> login_mgr -> error)
		{
			// Pass error message from manager		
			$this -> message = $this -> login_mgr -> last_error;
			
			// Keep user login in form
			$this -> user_login = $this -> login_mgr -> user_login;
			
			// Increase number of failed attemps
			$this -> login_attempts ++;
						
			// Draw form
			$this -> drawLoginForm();
		}
		else
		{
			// Draw redirect page
			if ( IN_ADMIN)
			{
				// Redirect user to ACP Index
				$this -> appCore -> output -> drawRedirect( $this -> appCore -> adminLink(), $this -> appCore -> lang['login_form_message_admin_done']);		
			}
			else
			{
				// Redirect user to Selected page
				$this -> appCore -> output -> drawRedirect( (strlen( $this -> appCore -> _POST( 'return_link')) > 0 ? $this -> appCore -> _POST( 'return_link') : $this -> appCore -> link()), $this -> appCore -> lang['login_form_message_done']);		
			}
		}
		
	}
	
	// ------------------------------------------------------------------------
	
	/**
	 * Logs user out
	 *
	 */
	
	function logoutUser(){
		
		// Are we in admin?
		if ( IN_ADMIN)
		{
			// Close Admin session
			$this -> appCore -> session -> destroyAdminSession( $this -> appCore -> user['id'] > 0);
			
			// Redirect user back to Log-In
			$this -> appCore -> output -> drawRedirect( $this -> appCore -> adminLink(), $this -> appCore -> lang['login_form_message_admin_closed']);		
		}
		else
		{
			// Close User Session
			$this -> appCore -> session -> closeSession();
			
			// Redirect user back to main Board Page
			$this -> appCore -> output -> drawRedirect( $this -> appCore -> link(), $this -> appCore -> lang['login_form_message_closed']);		
		}
	}
	
	// ------------------------------------------------------------------------
	
	/**
	 * Draws Log-In form page
	 *
	 */
	
	function drawLoginForm(){
				
		// Draw output. We use different approach for ACP and Frontend
		if ( IN_ADMIN)
		{
			// Draw Simple Page
			$this -> appCore -> output -> drawSimple( $this -> appCore -> lang['login_title'], $this -> appCore -> output -> loginForm( array(
				'login_message' 	=> $this -> message,
				'user_login' 		=> $this -> user_login
			)));
		}
		else
		{
			// Dont Allow quick Log In
			$this -> appCore -> output -> show_login = false;
			
			// Set message as event
			if ( isset( $this -> message[0]))
			{
				$this -> appCore -> output -> setEvent( $this -> message, $this -> appCore -> lang['login_error'], 0);
			}
			
			// Create Template
			$template = new tpl_login_page( $this -> appCore);
			
			// Set Some Basic TPL vars
			$tpl_vars = array(
				'user_login' 		=> $this -> user_login,
				'return_link'		=> $this -> appCore -> _POST( 'return_link')
			);
			
			// If we have to Log In for some strange reason, we gonna tell template about it
			if ( $this -> appCore -> conf['board_require_login'])
			{
				// Woop, we need to log-in!
				$tpl_vars['login_title'] = $this -> appCore -> lang['login_msg_required'];
				
				// Set message?
				if ( isset( $this -> appCore -> conf['board_require_login_reason'][0]))
				{
					// Set default reason
					$tpl_vars['login_message'] = nl2br( htmlspecialchars( $this -> appCore -> conf['board_require_login_reason']));
				}
				else
				{
					// Set default reason
					$tpl_vars['login_message'] = $this -> appCore -> lang['login_msg_required_reason'];
				}
			}
			
			// Pass Form some options from config
			$tpl_vars['login_op_hide'] = $this -> appCore -> conf['session_allow_hide'];
			$tpl_vars['login_op_remember'] = $this -> appCore -> conf['board_autolog_allow'];
			
			// Options checked?
			$tpl_vars['check_op_hide'] = $this -> appCore -> _REQ( 'login_hidden') == 1;
			$tpl_vars['check_op_remember'] = $this -> appCore -> _REQ( 'login_remember') == 1;
			
			// Show Register block?
			$tpl_vars['show_register'] = $this -> appCore -> conf['users_register_turn'];
			
			// Draw It
			$this -> appCore -> output -> draw( $this -> appCore -> lang['login_title'], array(), $template -> tpl_login_form( $tpl_vars));
		}
		
	}
	
}